package com.sskj.wechat.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.core.exception.MException;
import com.sskj.jgxt.jd.entity.ZhengGaiHuFu;
import com.sskj.jgxt.jd.vo.ZhengGaiHuFuVO;
import com.sskj.jgxt.trans.ZhengGaiHuFuTrans;
import com.sskj.personnel.domain.entity.EmployeeEntity;
import com.sskj.sys.domain.entity.MediaEntity;
import com.sskj.sys.repository.MediaRepository;
import com.sskj.utils.CalendarUtil;
import com.sskj.utils.HttpUtils;
import com.sskj.wechat.domain.vo.WeChatMediaVO;

@RestController
@RequestMapping("/wechat/upload")
public class WeChatUploadMediaServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MediaRepository mediaRepository;
	
	@Value("${sskj.conf.restUrl}")
	private String restUrl;
	

	@Value("${sskj.conf.mediaUploadPath}")
	private String mediaUploadPath;
	
	@SuppressWarnings("static-access")
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/jlFile", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "上传媒体数据")
	public void uploadFileFile(WeChatMediaVO file, HttpServletRequest request) {
		String fileBase64 = file.getMedataBase64();
		fileBase64 = fileBase64.substring(fileBase64.indexOf("base64,") + 7, fileBase64.length());
		file.setMedataBase64(fileBase64);
/*		String filename = file.getFilename();

		String path = CalendarUtil.dateToISO(Calendar.getInstance().getTime(), false) + "/"
				+ UUID.randomUUID().toString() + "/";*/
		/*cafile*/
		uploadJd(file);

	}	
	
	// 同步往监督系统
	public void uploadJd(WeChatMediaVO jl) {


		JSONObject obj = HttpUtils.httpPost(restUrl + "filecontrol/cahufu/up", jl);
		if (null == obj) {

		}

	}	

	@SuppressWarnings("static-access")
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/uploadMedia", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "上传媒体数据")
	public MediaEntity uploadImg(WeChatMediaVO file, HttpServletRequest request) {
		String fileBase64 = file.getMedataBase64();
		fileBase64 = fileBase64.substring(fileBase64.indexOf("base64,") + 7, fileBase64.length());
		// String path = mediaUploadPath;

		String filename = file.getFilename();

		String path = CalendarUtil.dateToISO(Calendar.getInstance().getTime(), false) + "/"
				+ UUID.randomUUID().toString() + "/";

		logger.info(path);

		File targetFile = new File(mediaUploadPath + path);
		// 生成图片保存的最终路径
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = null;

		Base64 base64 = new Base64();
		try {
			// //Base64解码
			byte[] bytes = base64.decodeBase64(new String(fileBase64).getBytes());
			// byte[] bytes=fileBase64.getBytes();
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			out = new FileOutputStream(mediaUploadPath + path + filename);
			byte[] buffer = new byte[1024];
			int byteread = 0;
			long alreadyRead = 0;
			int waitTime = 500;
			long daoTime = System.currentTimeMillis() + waitTime;
			request.getSession().setAttribute("uploadProgress", "0%");
			logger.info("进入了这里");
			while ((byteread = in.read(buffer)) != -1) {
				alreadyRead += byteread;
				if (System.currentTimeMillis() > daoTime) {
					logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了"
							+ (alreadyRead / bytes.length * 100) + "%");
					request.getSession().setAttribute("uploadProgress", (alreadyRead / bytes.length * 100) + "%");
					daoTime = System.currentTimeMillis() + waitTime;
				}
				out.write(buffer, 0, byteread); // 文件写操作
				out.flush();
			}
			out.close();
			request.getSession().setAttribute("uploadProgress", "100%");
			logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了" + (alreadyRead / bytes.length * 100)
					+ "%");

			// 将信息写入媒体entity
			MediaEntity wme = new MediaEntity();
			wme.setMedianame(filename);
			wme.setHttpurl("upload/" + path + filename);
			wme.setMediasize(bytes.length);
			wme.setMediaurl(mediaUploadPath + path + filename);
			wme.setAssociatedentity("MediaEntity");
			mediaRepository.save(wme);
			return wme;

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new MException("custom_msg", new Object[] { e.getMessage() });
		} catch (IOException e) {
			e.printStackTrace();
			throw new MException("custom_msg", new Object[] { e.getMessage() });
		}

	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/getMediaUploader", method = { RequestMethod.GET })
	@ControllerLogExeTime(description = "获取上传进度")
	public Map<String, Object> getMediaUploader(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String progress = (String) request.getSession().getAttribute("uploadProgress");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("progress", progress);
		return map;
	}

}
